package com.tony.blog.server.queue;

import com.tony.blog.api.utils.BlogMsg;
import com.tony.blog.api.utils.Constant;
import com.tony.blog.model.entity.BlogEntity;
import com.tony.blog.model.mapper.BlogMapper;
import com.tony.blog.server.lucene.LuceneBlogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.util.Objects;
import java.util.Optional;

/**
 * Created with IntelliJ IDEA.
 *
 * @Title: BlogQueueConsumer
 * @Auther: 皮蛋布丁
 * @Date: 2021/09/29/13:30
 * @Description: 事件启动模型解耦服务核心类(事件监听器)
 */
@Component
public class BlogQueueConsumer implements ApplicationListener<BlogMsg> {

    @Autowired
    private LuceneBlogService luceneBlogService;
    @Autowired
    private BlogMapper blogMapper;

    @Override
    public void onApplicationEvent(BlogMsg msg) {
        //根据不同的事件类型type执行不同的动作
        try {
            //博文的创建/恢复
            if (Objects.equals(msg.getType(), Constant.BlogIndexMsg.Create.getType()) || Objects.equals(msg.getType(),Constant.BlogIndexMsg.Active.getType())) {
                Optional<BlogEntity> optional =
                        Optional.ofNullable(blogMapper.selectByPK(msg.getBlogId()));
                if (optional.isPresent()) {
                    luceneBlogService.createDocument(optional.get());
                }
            //博文的删除/屏蔽
            } else if (Objects.equals(msg.getType(),Constant.BlogIndexMsg.Delete.getType()) || Objects.equals(msg.getType(),Constant.BlogIndexMsg.UnActive.getType())) {
                luceneBlogService.deleteDocument(msg.getBlogId());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
